import 'dart:async';
import 'dart:io';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

class Imagescanwidget extends StatefulWidget {
  // "com.imagepreview.plugin/router_channel")
  const Imagescanwidget({super.key});

  static const MethodChannel _channel =
      MethodChannel('com.imagepreview.plugin/router_channel');

  @override
  State<StatefulWidget> createState() {
    return _ImageScanWidgetState();
  }
}

class _ImageScanWidgetState extends State<Imagescanwidget> {
  // 图片列表
  List<String> imageUrls = [];
  int _currentPage = 0;
  int totalCount = 0;
  final int adFrequency = 3; // Frequency of ads
  late final PageController _pageController;
  bool _dataLoaded = false; // 数据初始化完成来初始化PageController

  @override
  void initState() {
    super.initState();
    _getInitialData();
    if (kDebugMode) {
      print("ImagePreview: initState _currentPage:  $_currentPage");
    }
  }

  @override
  dispose() {
    super.dispose();
    _pageController.dispose();
  }

  Future<void> _getInitialData() async {
    try {
      // 使用 Future.wait 确保两个异步调用按顺序执行
      final results = await Future.wait([
        Imagescanwidget._channel.invokeMethod('getImages'),
        Imagescanwidget._channel.invokeMethod('getIndex')
      ]);
      final List<dynamic>? data = results[0];
      final int? currentPage = results[1];
      // 打印data
      if (data != null) {
        if (kDebugMode) {
          print(
              'ImagePreview: _getInitialData to get data: $data , _currentPage: $_currentPage');
        }
        setState(() {
          imageUrls = data.cast<String>();
          _currentPage = currentPage!;
          totalCount = imageUrls.length + (imageUrls.length ~/ adFrequency);
          // 将 _currentPage 转换为totalCount的位置
          _currentPage = _currentPage + (_currentPage ~/ adFrequency);
          _pageController = PageController(initialPage: _currentPage);
          _dataLoaded = true;
        });
      }
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print('ImagePreview: Failed to get data: ${e.message}');
      }
    }
  }

  Widget _buildAdView(int index) {
    if (Platform.isAndroid) {
      return AndroidView(
        viewType: 'com.imagepreview.plugin/ad_view',
        creationParams: <String, dynamic>{
          'adUnitId': 'ca-app-pub-3940256099942544/6300978111',
          // pos 传递index
          'pos': index,
        },
        creationParamsCodec: StandardMessageCodec(),
      );
    } else if (Platform.isIOS) {
      return UiKitView(
        viewType: 'com.imagepreview.plugin/ad_view',
        creationParams: <String, dynamic>{
          'adUnitId': 'ca-app-pub-3940256099942544/6300978111',
          // pos 传递index
          'pos': index,
        },
        creationParamsCodec: StandardMessageCodec(),
      );
    } else {
      return const Text(
        '我是茶叶广告',
        style: TextStyle(fontSize: 24, color: Colors.black),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // Navigator.of(context).pushNamed("new_page", arguments: "hi"); 打开传递参数
    //获取路由参数
    // var args = ModalRoute.of(context)?.settings.arguments;
    // if (args != null) {
    //   imageUrls = args as List<String>;
    // }
    return Scaffold(
      appBar: AppBar(
        title: const Text('左右滑动图片预览'),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: () async {
              if (_dataLoaded) {
                final imageIndex =
                    _currentPage - (_currentPage ~/ (adFrequency + 1));
                if (kDebugMode) {
                  print(
                      "ImagePreview: _saveImage --- > imageIndex $imageIndex");
                }
                await _saveImage(imageUrls[imageIndex]);
              } else {
                ScaffoldMessenger.of(context)
                    .showSnackBar(const SnackBar(content: Text('数据加载中...')));
              }
            },
          ),
        ],
      ),
      body: _dataLoaded
          ? buildBody(context)
          : Container(
              color: Colors.black, // 深色背景
              child: const Center(
                child: CircularProgressIndicator(
                  value: 1,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ),
            ),
    );
  }

  void _handleSingleTap(BuildContext context, TapUpDetails details,
      PhotoViewControllerValue ctrValue) {
    // 获取屏幕宽度
    final screenWidth = MediaQuery.of(context).size.width;
    // 获取点击位置
    final tapPosition = details.globalPosition.dx;
    if (kDebugMode) {
      print(
          'ImagePreview: _handleSingleTap ---> screenWidth $screenWidth tapPosition $tapPosition');
    }
    // 如果点击位置在左半部分，向前翻页；在右半部分，向后翻页
    if (tapPosition < screenWidth / 2) {
      if (_pageController.page! > 0) {
        _pageController.previousPage(
          duration: const Duration(milliseconds: 350),
          curve: Curves.decelerate,
        );
      } else {
        // 如果是第一页，则不执行任何操作
        if (kDebugMode) {
          print('ImagePreview: _handleSingleTap ---> 已经是第一页');
        }
      }
    } else {
      if (_pageController.page! < totalCount - 1) {
        _pageController.nextPage(
          duration: const Duration(milliseconds: 350),
          curve: Curves.decelerate,
        );
      } else {
        if (kDebugMode) {
          print('ImagePreview: _handleSingleTap ---> 已经是最后一页');
        }
      }
    }
  }

  Widget buildBody(BuildContext context) {
    if (kDebugMode) {
      print('ImagePreview: buildBody totalCount: $totalCount');
    }
    return PhotoViewGallery.builder(
      itemCount: totalCount,
      builder: (context, index) {
        if ((index + 1) % (adFrequency + 1) == 0) {
          // Insert ad view at calculated positions
          return PhotoViewGalleryPageOptions.customChild(
            onTapUp: _handleSingleTap,
            child: Center(
              child: Container(
                color: Colors.white,
                width: 300,
                height: 250,
                child: Center(
                  // Display your ad view here
                  // Test1: flutter view.
                  child: Center(child: _buildAdView(index)),
                ),
              ),
            ),
            minScale: PhotoViewComputedScale.contained,
            maxScale: PhotoViewComputedScale.contained,
          );
        } else {
          final imageIndex = index - (index ~/ (adFrequency + 1));
          if (kDebugMode) {
            print(
                'ImagePreview: builder imageIndex: $imageIndex imageUrl: ${imageUrls[imageIndex]}');
          }
          return PhotoViewGalleryPageOptions(
            onTapUp: _handleSingleTap,
            imageProvider: NetworkImage(imageUrls[imageIndex]),
            minScale: PhotoViewComputedScale.contained * 0.8,
            maxScale: PhotoViewComputedScale.covered * 2,
            heroAttributes: PhotoViewHeroAttributes(tag: index.toString()),
          );
        }
      },
      scrollPhysics: const ClampingScrollPhysics(),
      backgroundDecoration: const BoxDecoration(color: Colors.black),
      // 设置加载中的占位符背景颜色为深色
      loadingBuilder: (context, event) => Container(
        color: Colors.black, // 深色背景
        child: Center(
          child: CircularProgressIndicator(
            value: event == null
                ? null
                : event.cumulativeBytesLoaded / (event.expectedTotalBytes ?? 1),
            valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
      ),
      pageController: _pageController,
      onPageChanged: (index) {
        // 页面切换回调
        setState(() {
          _currentPage = index;
        });
      },
    );
  }

  Future<void> _saveImage(String imageUrl) async {
    try {
      // 请求存储权限
      if (await requestPhotoPermission()) {
        await saveToGallery(imageUrl);
      } else {
        ScaffoldMessenger.of(context)
            .showSnackBar(const SnackBar(content: Text('没有获取到相册权限')));
      }
    } catch (e) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('保存失败:')));
    }
  }

  Future<void> saveToGallery(String imageUrl) async {
    // 使用 CachedNetworkImageProvider 获取图片数据
    final imageProvider = CachedNetworkImageProvider(imageUrl);
    final imageStream = imageProvider.resolve(const ImageConfiguration());

    // 使用 Completer 来等待图片加载完成
    Completer<Uint8List> completer = Completer<Uint8List>();
    // 定义 ImageStreamListener
    ImageStreamListener? listener;
    listener = ImageStreamListener((ImageInfo info, bool syncCall) {
      // 将图片数据保存到相册
      final image = info.image;
      image.toByteData(format: ImageByteFormat.png).then((byteData) {
        final uint8List = byteData!.buffer.asUint8List();
        completer.complete(uint8List as FutureOr<Uint8List>?);
        imageStream.removeListener(listener!);
      });
    }, onError: (dynamic exception, StackTrace? stackTrace) {
      if (kDebugMode) {
        print('ImagePreview: Error loading image: $exception');
      }
      completer.completeError(exception, stackTrace);
    });

    imageStream.addListener(listener);

    final uint8List = await completer.future;
    final result = await ImageGallerySaver.saveImage(uint8List, quality: 100);

    if (result['isSuccess']) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('图片已保存到相册')));
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('保存失败')));
    }
  }

  Future<bool> requestPhotoPermission() async {
    try {
      if (Platform.isIOS) {
        // 请求相册权限
        var photosStatus = await Permission.photos.status;
        if (!photosStatus.isGranted) {
          photosStatus = await Permission.photos.request();
        }

        if (photosStatus.isPermanentlyDenied) {
          handlePermanentDenial("相册权限");
          return false;
        }

        if (!photosStatus.isGranted) {
          return false;
        }
      }

      // 请求存储权限（仅在 Android 上需要）
      if (Platform.isAndroid) {
        var storageStatus = await Permission.storage.status;
        if (!storageStatus.isGranted) {
          storageStatus = await Permission.storage.request();
        }

        if (storageStatus.isPermanentlyDenied) {
          handlePermanentDenial("存储权限");
          return false;
        }

        if (!storageStatus.isGranted) {
          return false;
        }
      }

      return true;
    } catch (e) {
      if (kDebugMode) {
        print("ImagePreview: 权限请求过程中发生错误: $e");
      }
      return false;
    }
  }

  void handlePermanentDenial(String permissionType) {
    if (kDebugMode) {
      print("ImagePreview: $permissionType 被永久拒绝，请前往设置中手动开启");
    }
    openAppSettings(); // 打开应用设置界面
  }
}
